package com.yolib.sanyi.pic;

import java.io.File;
import java.lang.ref.SoftReference;
import java.util.LinkedHashMap;


import android.content.Context;
import android.graphics.Bitmap;
import android.support.v4.util.LruCache;
import android.util.Log;


public class MemoryCache {
	private static final int hardCachedSize = 4*1024*1024;	

	private final LruCache<String, Bitmap> sHardBitmapCache; 
	static MemoryCache memoryCache;
	public MemoryCache(){
		sHardBitmapCache = new LruCache<String, Bitmap> (hardCachedSize){
			@Override
			public int sizeOf(String key, Bitmap value){
				return value.getRowBytes() * value.getHeight();
			}
			@Override
			protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue){
				//sSoftBitmapCache.put(key, new SoftReference<Bitmap>(oldValue));
			}
		};
	}

	public static MemoryCache getInstance()
	{
		if(memoryCache == null)
			memoryCache = new MemoryCache();
		return memoryCache;
	}

	public static void clearMemoryCache()
	{
		memoryCache = null;
	}

	//hard cache

	private static final int SOFT_CACHE_CAPACITY = 40;
	private final static LinkedHashMap<String, SoftReference<Bitmap>> sSoftBitmapCache = 
			new  LinkedHashMap<String, SoftReference<Bitmap>>(SOFT_CACHE_CAPACITY, 0.75f, true){

		private static final long serialVersionUID = 1L;

		@Override
		public SoftReference<Bitmap> put(String key, SoftReference<Bitmap> value){
			return super.put(key, value);
		}

		protected boolean removeEldestEntry(java.util.Map.Entry<String,java.lang.ref.SoftReference<Bitmap>> eldest) 
		{
			if(size() > SOFT_CACHE_CAPACITY){
				return true;
			}
			return false;
		}
	};

	public boolean putBitmap(String key, Bitmap bitmap){
		if(bitmap != null){
			synchronized(sHardBitmapCache){
				sHardBitmapCache.put(key, bitmap);
			}
			return true;
		}		
		return false;
	}

	public Bitmap getBitmap(String key){
		synchronized(sHardBitmapCache){
			final Bitmap bitmap = sHardBitmapCache.get(key);
			if(bitmap != null)
			{
				return bitmap;
			}
		}
		SoftReference<Bitmap> bitmapReference = sSoftBitmapCache.get(key);
		if(bitmapReference != null){
			final Bitmap bitmap2 = bitmapReference.get();
			if(bitmap2 != null)
			{
				return bitmap2;
			}
			else{
				sSoftBitmapCache.remove(key);
			}
		}
		return null;
	}


}
